import { WSConfig, sqlConnect, tmqConnect, TMQConstants } from "@tdengine/websocket";

const createConnection = async () => {
    const conf = new WSConfig("ws://localhost:6041");
    conf.setUser("root")
    conf.setPwd("taosdata")
    conf.setDb("test")
    return await sqlConnect(conf);
}

const query = async () => {
    const wsSql = await createConnection();
    // console.log(wsSql);
    const rows = await wsSql.query("select * from test.meters limit 10");
    // console.log(rows.getData())
    while (await rows.next()) {
        console.log(rows.getData());
    }
}

const consumer = async () => {
    const confMap = new  Map([
        [TMQConstants.GROUP_ID, "group1"],
        [TMQConstants.CLIENT_ID, "client1"],
        [TMQConstants.CONNECT_USER, "root"],
        [TMQConstants.CONNECT_PASS, "taosdata"],
        [TMQConstants.WS_URL, "ws://localhost:6041"],
        [TMQConstants.ENABLE_AUTO_COMMIT, "true"],
        [TMQConstants.AUTO_COMMIT_INTERVAL_MS, "1000"]
    ])
    const conn = await tmqConnect(confMap);
    return conn;
}

const subscribe = async () => {
    try {
        var wsConsumer = await consumer();
        console.info(wsConsumer);
        await wsConsumer.subscribe(['topic_meters']);
        for (let i = 0; i < 50; i++) {
            let res = await wsConsumer.poll(100);
            // @ts-ignore
            for (let [key, value] of res) {
                console.log(`data: ${key} ${value}`);
            }
            await wsConsumer.commit();
            console.log("Commit offset manually successfully.");
        }
    } catch (e) {
        console.error(e);
    }
}

async function test() {
    await query();
    // await consumer();
    // await subscribe();
}

test()